if (!(process.env.SKIP_CYPRESS_INSTALL || process.env.BUILD_REPO_NAME)) {
  const fs = require('fs')
  const os = require('os')
  const path = require('path')

  const chalk = require('chalk')
  const { getVersions } = require('cypress/lib/exec/versions')
  const { start } = require('cypress/lib/tasks/install')
  const request = require('request')

  const distPath = path.join(__dirname, 'cache', 'cypress.zip')

  const dest = fs.createWriteStream(distPath)

  void (async () => {
    const { binary: binaryVersion, package: version } = await getVersions()
    if (binaryVersion === version) {
      console.info(chalk.bgBlack(chalk.green(`Found local cypress version: ${version}, skip install`)))
      process.exit(0)
    }
    if (!fs.existsSync(distPath) || !fs.readFileSync(distPath).length) {
      await new Promise((resolve) =>
        request(`https://bnpm.bytedance.net/mirrors/cypress/${version}/${os.platform()}/cypress.zip`, {
          method: 'GET',
        })
          .pipe(dest)
          .on('error', (e) => {
            console.error(e)
            process.exit(1)
          })
          .on('finish', resolve),
      )
    }

    process.env.CYPRESS_INSTALL_BINARY = path.join(__dirname, 'cache', 'cypress.zip')

    await start({
      force: true,
    })
  })()
}
